const express = require("express"),
app = express(),
Gpio = require('onoff').Gpio,
path = require("path"),
os = require('os');

app.use("/", express.static(path.join(__dirname, "public")));
app.use("/appleOn", express.static(path.join(__dirname, "public/appleOn")));
app.use("/appleOff", express.static(path.join(__dirname, "public/appleOff")));
app.use('/static', express.static('static'));

let TimeNum = 0;
const led = new Gpio(16, 'out'),
LanIP = os.networkInterfaces().wlan0[0].address;

function detectionTime() { // power on self test
let hours = new Date().getHours();
if (hours < 18) {
    console.log(led);
    led.writeSync(0);
    console.log("now is turn off LED Time");
} else if (hours > 18) {
    led.writeSync(1);
    console.log("now is turn on LED Time");
}
}

detectionTime();

setInterval(function () {
TimeNum = TimeNum + 1; //console.log(TimeNum);
if (TimeNum === 300) { //5 min is shutdown
    TimeNum = 0;
    detectionTime();
}
}, 1000);

function gpioState(urlPath) {
if (urlPath === "/on") {
    led.writeSync(1);
}
if (urlPath === "/off") {
    led.writeSync(0);
}
}

app.get("/on", function (req, res) {
gpioState(req.path);
res.json("ON");
//console.log(led.readSync());
//console.log(led.direction());
});

app.get("/off", function (req, res) {
gpioState(req.path);
res.json("OFF");
});

app.get("/appleOn/on", function (req, res) {
led.writeSync(1);
res.json("ON");
});

app.get("/appleOff/off", function (req, res) {
led.writeSync(0);
res.json("OFF");
});

app.get("/state", function (req, res) {
let state = led.readSync();
console.log(state);
res.json(state);
});

let server = app.listen(3000, LanIP, () => {
let host = server.address().address;
let port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});